package com.example.core.shiroLogin;

import com.example.core.util.Result;
import org.apache.catalina.Role;
import org.apache.catalina.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName HomeIndexController
 * @Author zhangzhaoyang
 * @Date 2019/10/16 10:31
 **/
@Controller
public class HomeIndexController {
    private static Logger logger = LoggerFactory.getLogger(HomeIndexController.class);

    /**
     * 登陆一定要是post请求
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletResponse response) throws IOException {
        logger.info("===登陆页面信息——>用户名："+username+",密码："+password);
        ModelAndView modelAndView = new ModelAndView();
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();


        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        // 执行认证登陆
        try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
//            return "未知账户";
            logger.info("===未知账户==="+uae.getMessage());
            modelAndView.setViewName("/login");
            modelAndView.addObject("未知账户");
            //           下面代码是为了方便开发
            response.setContentType("text/html;charset=gb2312");
            PrintWriter out = response.getWriter();
            out.print("<script language=\"javascript\">alert('未知账户！')</script>");
            modelAndView.addObject(out);
            return modelAndView;

        } catch (IncorrectCredentialsException ice) {
            logger.info("===密码不正确==="+ice.getMessage());
            modelAndView.setViewName("/login");
            modelAndView.addObject("密码不正确");
            //           下面代码是为了方便开发
            response.setContentType("text/html;charset=gb2312");
            PrintWriter out = response.getWriter();
            out.print("<script language=\"javascript\">alert('密码不正确！')</script>");
            modelAndView.addObject(out);
            return modelAndView;

        } catch (LockedAccountException lae) {
            logger.info("===账户已锁定==="+lae.getMessage());
            modelAndView.setViewName("/login");
            modelAndView.addObject("账户已锁定");
            //           下面代码是为了方便开发
            response.setContentType("text/html;charset=gb2312");
            PrintWriter out = response.getWriter();
            out.print("<script language=\"javascript\">alert('账户已锁定！')</script>");
            modelAndView.addObject(out);
            return modelAndView;

        } catch (ExcessiveAttemptsException eae) {
//            return "用户名或密码错误次数过多";
            logger.info("===用户名或密码错误次数过多==="+eae.getMessage());
            modelAndView.setViewName("/login");
            modelAndView.addObject("用户名或密码错误次数过多");
            //           下面代码是为了方便开发
            response.setContentType("text/html;charset=gb2312");
            PrintWriter out = response.getWriter();
            out.print("<script language=\"javascript\">alert('用户名或密码错误次数过多！')</script>");
            modelAndView.addObject(out);
            return modelAndView;
        } catch (AuthenticationException ae) {
//            return "用户名或密码不正确！";
            logger.info("===用户名或密码不正确==="+ae.getMessage());
            modelAndView.setViewName("/login");
            modelAndView.addObject("用户名或密码不正确");
            //           下面代码是为了方便开发
            response.setContentType("text/html;charset=gb2312");
            PrintWriter out = response.getWriter();
            out.print("<script language=\"javascript\">alert('用户名或密码不正确！')</script>");
            modelAndView.addObject(out);
            return modelAndView;
        }


        /**
         * 当subject验证通过就登陆
         */
        if (subject.isAuthenticated()) {
//            跳转首页
            logger.info("===成功页面===");
            modelAndView.setViewName("/index");
            //           下面代码是为了方便开发
            response.setContentType("text/html;charset=gb2312");
            PrintWriter out = response.getWriter();
            out.print("<script language=\"javascript\">alert('登录成功！')</script>");
            modelAndView.addObject(out);
            return modelAndView;


        } else {
            token.clear();
            modelAndView.setViewName("/login");
            modelAndView.addObject("登录失败");
//           下面代码是为了方便开发
            response.setContentType("text/html;charset=gb2312");
            PrintWriter out = response.getWriter();
            out.print("<script language=\"javascript\">alert('登录失败！')</script>");
            modelAndView.addObject(out);
            return modelAndView;
        }
    }

}
